package game.logic.app;

import javax.swing.JComponent;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Objects;

public class PuzzleBrick extends JComponent
{
    public static final int UNIT_SIZE = 64;

    private final char id;
    private final Color color;
    private final int xUnits;
    private final int yUnits;
    private final boolean barrier;

    private boolean vertical;

    public PuzzleBrick(char id, Color color, int xUnits, int yUnits, boolean barrier)
    {
        this.id = id;
        this.color = color;
        this.xUnits = Math.max(xUnits, yUnits);
        this.yUnits = Math.min(xUnits, yUnits);
        this.barrier = barrier;

        // 初始状态是水平放置的（xUnits >= yUnits）。
        vertical = false;

        Dimension size = new Dimension(getWidth(), getHeight());
        setPreferredSize(size);
        setMinimumSize(size);
        setMaximumSize(size);
    }

    public char getId()
    {
        return id;
    }

    public boolean isBarrier()
    {
        return barrier;
    }

    public boolean isVertical()
    {
        return vertical;
    }

    public boolean isSquare()
    {
        return xUnits == yUnits;
    }

    public int getXUnits()
    {
        return vertical ? yUnits : xUnits;
    }

    public int getYUnits()
    {
        return vertical ? xUnits : yUnits;
    }

    public void rotate()
    {
        vertical = !vertical;
        if (xUnits != yUnits)
        {
            Dimension size = new Dimension(getWidth(), getHeight());
            setPreferredSize(size);
            setMinimumSize(size);
            setMaximumSize(size);
            repaint();
        }
    }

    public void reset()
    {
        vertical = false;
        Dimension size = new Dimension(getWidth(), getHeight());
        setPreferredSize(size);
        setMinimumSize(size);
        setMaximumSize(size);
        repaint();
    }

    @Override
    public int getWidth()
    {
        return vertical ? UNIT_SIZE * yUnits : UNIT_SIZE * xUnits;
    }

    @Override
    public int getHeight()
    {
        return vertical ? UNIT_SIZE * xUnits : UNIT_SIZE * yUnits;
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setPaint(color);
        g2d.fillRoundRect(4, 4, getWidth() - 8, getHeight() - 8, 8, 8);
        g2d.dispose();
    }

    @Override
    public boolean equals(Object o)
    {
        if (o == null || getClass() != o.getClass()) return false;
        PuzzleBrick brick = (PuzzleBrick) o;
        return id == brick.id;
    }

    @Override
    public int hashCode()
    {
        return Objects.hashCode(id);
    }
}
